package fictional.GUI;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.jdesktop.application.Application;

import fictional.Common.CharacterItem;
import fictional.Common.FriendRequests;
import fictional.Common.IBL;
import fictional.Common.Response;
import fictional.Common.ShortCharacterItem;

/**
 * This task either searches for friends by name, or
 * finds recommended friends for a character.
 */
public class SearchFriendsTask extends DefaultTask
{
	String searchedText;
	CharacterItem character;
	
    public SearchFriendsTask(Application application)
	{
		super(application);
	}
    
    public void setSearchTask(IBL BL, String searchedText, GUI gui, CharacterItem character)
    {
        this.BL = BL;
        this.gui = gui;
        this.searchedText = searchedText;
        this.character = character;
    }
    
    public void setSuggestTask(IBL BL, GUI gui, CharacterItem character)
    {
        this.BL = BL;
        this.gui = gui;
        this.character = character;
    }

    @Override
    protected Object doInBackground() throws IOException, InterruptedException
    {
        response = new Response();
    	List<ShortCharacterItem> searchResults;
        
        if (searchedText == null)
        {
        	searchResults = BL.getSuggestedCharacters(character, response);
        }
        else
        {
        	searchResults = BL.getShortCharacterByName(searchedText, response);
        }
    	
    	ArrayList<ShortCharacterItem> searchResultsArray = new ArrayList<ShortCharacterItem>(searchResults);
    	if (response.isIs_Success())
    	{
        	if (searchResults.size() == 0)
        	{
        		response.setIs_Success(false);
        		errorTitle = "Search For Friends";
        		if (searchedText == null)
        		{
            		response.setMessage("No friend suggetions found!");
        		}
        		else
        		{
            		response.setMessage("No friends found!");
        		}
        		return null;
        	}
        	
        	FriendRequests friendRequestsSent = BL.getFriendRequests(character, false, response);
        	FriendRequests friendRequestsReceived = BL.getFriendRequests(character, true, response);
        	if (response.isIs_Success())
        	{
        		gui.searchFriends(searchResultsArray, friendRequestsSent, friendRequestsReceived);
        	}
        	else
        	{
        		errorTitle = "Error Searching For Friends";
        	}	
    	}
    	else
    	{
    		errorTitle = "Error Searching For Friends";
    	}	
        
        return null;
    }
}
